﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;

public partial class Main_Reports_Accounts_ProfitAndLoss : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    AccountSettings ASettings = new AccountSettings();
    string strSql = string.Empty;
    double dblTotalExp = 0;
    double dblTotalIncome = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            hidFinyear.Value = Session["FINYEAR"].ToString();
            string strFromDate = "01/04/" + Session["FINYEAR"].ToString();
            string strToDate = "31/03/" + (int.Parse(Session["FINYEAR"].ToString()) + 1).ToString();
            _GetProfitAndLoss(strFromDate, strToDate);            
        }
    }
    protected void btnCangeDate_Click(object sender, EventArgs e)
    {
        _GetProfitAndLoss(txtFromDate.Text, txtToDate.Text);
    }
    private void _GetProfitAndLoss(string strFromDate, string strToDate)
    {

        if (strFromDate != string.Empty && strToDate != string.Empty)
        {
            lblCompanyName.Text = Session["compname"].ToString();
            lblHeading.Text = "Profit & Loss A/c from " + Convert.ToDateTime(strFromDate).ToString("dd-MMM-yyyy") + " To " + Convert.ToDateTime(strToDate).ToString("dd-MMM-yyyy") + " .";
            string[] arrStr = strFromDate.ToString().Split('/');
            strFromDate = arrStr[1] + "/" + arrStr[0] + "/" + arrStr[2];
            arrStr = strToDate.ToString().Split('/');
            strToDate = arrStr[1] + "/" + arrStr[0] + "/" + arrStr[2];

            SqlParameter[] sparam ={
                                        new SqlParameter("@FROMDATE",strFromDate),
                                        new SqlParameter("@TODATE",strToDate),                    
                                        new SqlParameter("@ISFIRSTYEAR",_IsFirstYear(Session["FINYEAR"].ToString())),          
                                        new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                          
                                       };
            DataTable DTProfit = DU.getdatausingprocedure("USP_ACC_GetProfitAndLoss", sparam);

            DataTable DTMain = new DataTable();            
            DTMain.Columns.Add("ExpGID", typeof(string));
            DTMain.Columns.Add("ExpGroup", typeof(string));
            DTMain.Columns.Add("ExpActTotal", typeof(string));
            DTMain.Columns.Add("ExpTotal", typeof(string));
            DTMain.Columns.Add("IncGID", typeof(string));
            DTMain.Columns.Add("IncGroup", typeof(string));
            DTMain.Columns.Add("IncActTotal", typeof(string));
            DTMain.Columns.Add("IncTotal", typeof(string));

            DataView dvExp = DTProfit.DefaultView;
            dvExp.RowFilter = "ExpensesIncome='1'";
            DataTable dtExpGroup = dvExp.ToTable();

            DataView dvInc = DTProfit.DefaultView;
            dvInc.RowFilter = "ExpensesIncome='2'";
            DataTable dtIncomeGroup = dvInc.ToTable();

            DataView dvPL = DTProfit.DefaultView;
            dvPL.RowFilter = "ExpensesIncome='3'";
            DataTable dtPL = dvPL.ToTable();

            int totalRowCount = 0;
            if (dtExpGroup.Rows.Count > dtIncomeGroup.Rows.Count)
            {
                totalRowCount = dtExpGroup.Rows.Count;
            }
            else
            {
                totalRowCount = dtIncomeGroup.Rows.Count;
            }
            for (int i = 0; i < totalRowCount; i++)
            {
                DataRow DRMain = DTMain.NewRow();
                string strExpGID = string.Empty;
                string strExpGName = string.Empty;
                string strExpActTotal = string.Empty;
                string strExpTotal = string.Empty;
                string strIncGID = string.Empty;
                string strIncGName = string.Empty;
                string strIncActTotal = string.Empty;
                string strIncTotal = string.Empty;

                if (i < dtExpGroup.Rows.Count)
                {
                    strExpGID = dtExpGroup.Rows[i]["GID"].ToString();
                    strExpGName = dtExpGroup.Rows[i]["GNAME"].ToString();
                    strExpActTotal = dtExpGroup.Rows[i]["ACTGROUPTOTAL"].ToString();
                    strExpTotal = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dtExpGroup.Rows[i]["GROUPTOTAL"].ToString())))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");

                }
                if (i < dtIncomeGroup.Rows.Count)
                {
                    strIncGID = dtIncomeGroup.Rows[i]["GID"].ToString();
                    strIncGName = dtIncomeGroup.Rows[i]["GNAME"].ToString();
                    strIncActTotal = dtIncomeGroup.Rows[i]["ACTGROUPTOTAL"].ToString();
                    strIncTotal = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dtIncomeGroup.Rows[i]["GROUPTOTAL"].ToString())))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
                }
                DRMain["ExpGID"] = strExpGID.ToString();
                DRMain["ExpGroup"] = strExpGName.ToString();
                DRMain["ExpActTotal"] = strExpActTotal.ToString();
                DRMain["ExpTotal"] = strExpTotal.ToString();
                DRMain["IncGID"] = strIncGID.ToString();
                DRMain["IncGroup"] = strIncGName.ToString();
                DRMain["IncActTotal"] = strIncActTotal.ToString();
                DRMain["IncTotal"] = strIncTotal.ToString();             

                DTMain.Rows.Add(DRMain);
            }            

           
            if (dtPL.Rows.Count > 0)//for profit & loss amount 
            {
                DataRow DRMain1 = DTMain.NewRow();
                if (dtPL.Rows[0]["ACTGROUPTOTAL"].ToString() != string.Empty)
                {
                    string strExpGID = string.Empty;
                    string strExpGName = string.Empty;
                    string strExpActTotal = string.Empty;
                    string strExpTotal = string.Empty;
                    string strIncGID = string.Empty;
                    string strIncGName = string.Empty;
                    string strIncActTotal = string.Empty;
                    string strIncTotal = string.Empty;

                    if (Convert.ToDouble(dtPL.Rows[0]["ACTGROUPTOTAL"].ToString()) > 0)
                    {
                        strIncGName = dtPL.Rows[0]["GNAME"].ToString();
                        strIncTotal = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dtPL.Rows[0]["GROUPTOTAL"].ToString())))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
                        strIncActTotal = dtPL.Rows[0]["ACTGROUPTOTAL"].ToString();
                        strIncGID = dtPL.Rows[0]["GID"].ToString();
                    }
                    else
                    {
                        strExpGID = dtPL.Rows[0]["GID"].ToString();
                        strExpGName = dtPL.Rows[0]["GNAME"].ToString();
                        strExpTotal = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dtPL.Rows[0]["GROUPTOTAL"].ToString())))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
                        strExpActTotal = dtPL.Rows[0]["ACTGROUPTOTAL"].ToString();
                    }
                    DRMain1["ExpGID"] = strExpGID.ToString();
                    DRMain1["ExpGroup"] = strExpGName.ToString();
                    DRMain1["ExpActTotal"] = strExpActTotal.ToString();
                    DRMain1["ExpTotal"] = strExpTotal.ToString();
                    DRMain1["IncGID"] = strIncGID.ToString();
                    DRMain1["IncGroup"] = strIncGName.ToString();
                    DRMain1["IncActTotal"] = strIncActTotal.ToString();
                    DRMain1["IncTotal"] = strIncTotal.ToString();
                    DTMain.Rows.Add(DRMain1);
                }
            }            

            grdProfitAndLoss.DataSource = DTMain;
            grdProfitAndLoss.DataBind();


        }
    }
    protected void grdProfitAndLoss_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {            
            e.Row.Cells[1].Text = "Amount(" + ASettings.GetCurrencySymbol() + ")";
            e.Row.Cells[3].Text = "Amount(" + ASettings.GetCurrencySymbol() + ")";
            e.Row.Cells[1].Style.Add("border-right", "solid 1px #d6d3ce");            
            e.Row.Style.Add("border-bottom", "solid 1px #d6d3ce");
            e.Row.Cells[0].Style.Add("border-bottom", "solid 1px #d6d3ce");
            e.Row.Cells[1].Style.Add("border-bottom", "solid 1px #d6d3ce");
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Cells[1].Style.Add("border-right", "solid 1px #d6d3ce");
            e.Row.Style.Add("border-bottom", "solid 1px #d6d3ce");   

            HiddenField hidExpGID = (HiddenField)e.Row.FindControl("hidExpGID");
            Label lblExpAmount = (Label)e.Row.FindControl("lblExpAmount");
            HiddenField hidExpActAmount = (HiddenField)e.Row.FindControl("hidExpActAmount");
            if (hidExpActAmount.Value != string.Empty)
            {
                if (Convert.ToDouble(hidExpActAmount.Value) > 0)
                {
                    lblExpAmount.Text = ASettings.GetCurrency(0 - Math.Abs(Convert.ToDouble(hidExpActAmount.Value)));
                }
                else
                {
                    lblExpAmount.Text = ASettings.GetCurrency(Math.Abs(Convert.ToDouble(hidExpActAmount.Value)));
                }
                dblTotalExp += Convert.ToDouble(hidExpActAmount.Value);
            }            

            HiddenField hidIncGID = (HiddenField)e.Row.FindControl("hidIncGID");
            Label lblIncAmount = (Label)e.Row.FindControl("lblIncAmount");
            HiddenField hidIncActAmount = (HiddenField)e.Row.FindControl("hidIncActAmount");
            if (hidIncActAmount.Value != string.Empty)
            {
                if (Convert.ToDouble(hidIncActAmount.Value) < 0)
                {
                    lblIncAmount.Text = ASettings.GetCurrency(0 - Math.Abs(Convert.ToDouble(hidIncActAmount.Value)));
                }
                else
                {
                    lblIncAmount.Text = ASettings.GetCurrency(Math.Abs(Convert.ToDouble(hidIncActAmount.Value)));
                }
                dblTotalIncome += Convert.ToDouble(hidIncActAmount.Value);
            }

            if (e.Row.Cells[0].Text == "Net Profit" || e.Row.Cells[0].Text == "Net Loss")
            {
                e.Row.Cells[0].Font.Bold = true;
            }
            if (e.Row.Cells[2].Text == "Net Profit" || e.Row.Cells[2].Text == "Net Loss")
            {
                e.Row.Cells[2].Font.Bold = true;
            } 
        
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "Total  ";
            e.Row.Cells[1].Text = ASettings.GetCurrency(Math.Abs(Convert.ToDouble(dblTotalExp))); 
            e.Row.Cells[2].Text = "Total  ";
            e.Row.Cells[3].Text = ASettings.GetCurrency(Math.Abs(Convert.ToDouble(dblTotalIncome))); 
            e.Row.Font.Bold = true;
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
            e.Row.Cells[1].Style.Add("border-right", "solid 1px #d6d3ce");

        }
    }
    private string _IsFirstYear(string strFinYear)
    {
        string strIsFirstYear = string.Empty;
        strSql = "SELECT MIN(FINYEAR)AS FINYEAR FROM MAS_FINYEAR";
        DataTable DTMinFinyear = DU.getdata(strSql);
        if (DTMinFinyear.Rows.Count > 0)
        {
            if (Convert.ToInt32(DTMinFinyear.Rows[0]["FINYEAR"].ToString()) == Convert.ToInt32(strFinYear))
            {
                strIsFirstYear = "1";
            }
            else
            {
                strIsFirstYear = "0";
            }
        }
        return strIsFirstYear;
    }
}
